package com.example.qsindusty.jmm_spline.SearchActiviity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.qsindusty.jmm_spline.Config.Config;
import com.example.qsindusty.jmm_spline.OrdeFragment.OrderData;
import com.example.qsindusty.jmm_spline.OrderinfoActivity.OrderInfoActivity;
import com.example.qsindusty.jmm_spline.R;
import com.yixin.ystartlibrary.base.BaseAppCompatActivity;
import com.yixin.ystartlibrary.base.BaseRecyclerAdapter;
import com.yixin.ystartlibrary.utils.DensityUtil;
import com.yixin.ystartlibrary.utils.GeneralPreferencesUtils;
import com.yixin.ystartlibrary.utils.LoadingDialogUtils;
import com.yixin.ystartlibrary.utils.LogUtils;
import com.yixin.ystartlibrary.utils.StatusBarUtil;
import com.yixin.ystartlibrary.utils.ToastUtils;
import com.yixin.ystartlibrary.widget.DiverItemDecoration;
import com.yixin.ystartlibrary.widget.EmptyRecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchActivity extends BaseAppCompatActivity implements  ContarctSearch.View {
    Menu mMenu;
    @BindView(R.id.id_empty_recyclerview)
    EmptyRecyclerView recyclerview;
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;
    @BindView(R.id.empty_text)
    TextView emptyText;
    String row = Config.row;//默认为10条
    String page = Config.page; //
   //默认为2未接货  未分配司机，已分配司机，未接货 运输中 已完成0-4
    OrderAdapter orderAdapter;
    @BindView(R.id.mlinearlayout)
    LinearLayout mlinearlayout;
    SearchPresenter mPresenter ;
    EditText editText ;
     String token ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
         editText = new EditText(this);
        LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
                (int) (DensityUtil.getWidth(mActivity)*0.6), LinearLayout.LayoutParams.WRAP_CONTENT);
        layout.gravity=Gravity.CENTER ;
        editText.setLayoutParams(layout);
        editText.setBackgroundResource(R.drawable.textinouteidtetext);
        editText.setHint("订单号/司机/车辆/企业/发件人/收件人");
        editText.setTextSize(12);
        editText.setSingleLine();
        StatusBarUtil.immersive(this.getWindow());
        mToolbarTitle.setVisibility(View.GONE);
        StatusBarUtil.setPaddingSmart(this, mToolBar);
        mToolBar.addView(editText);
        setEnabledNavigation(true);
        bindPresenter();
        initview();

    }

    private void initview() {
        orderAdapter = new OrderAdapter();
        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        DiverItemDecoration itemDecoration = new DiverItemDecoration(DiverItemDecoration.VERTICAL);
        itemDecoration.setSize(DensityUtil.dip2px(this, 0.5f));
        itemDecoration.setColor(ContextCompat.getColor(this, R.color.default_layout_color));
        emptyText.setText("点击重新加载");
        recyclerview.addItemDecoration(itemDecoration);
        //解决ScrollView嵌套RecyclerView滑动卡帧
        recyclerview.setNestedScrollingEnabled(false);
        //色通知
        recyclerview.setEmptyView(LayoutInflater.from(this).inflate(R.layout.item_emptyview, null));
        recyclerview.setAdapter(orderAdapter);
         token= GeneralPreferencesUtils.getSharedPreference(this,Config.token,null);

        recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager();
                int totalItemCount = recyclerView.getAdapter().getItemCount();
                int lastVisibleItemPosition = lm.findLastVisibleItemPosition();
                int visibleItemCount = recyclerView.getChildCount();
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItemPosition == totalItemCount - 1
                        && visibleItemCount > 0) {
                    //加载更多
                    ToastUtils.showLongToast(mActivity,"加不加哟");
                    page=page+1;
                    mPresenter.searchOrder(token,row,page,editText.getText().toString().trim());
                }


            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

            }
        });
    }


    @Override
    protected void init() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
            unbindPresenter();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_search, menu);
        mMenu = menu;
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.search_icon).setVisible(true);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.search_icon:
                LogUtils.i(editText.getText().toString().trim());
                mPresenter.searchOrder(token,row,page,editText.getText().toString().trim());
                break;
        }

        return false;
    }

    @OnClick(R.id.iv_empty)
    public void onIvEmptyClicked() {
    }

    @OnClick(R.id.empty_text)
    public void onEmptyTextClicked() {
    }

    AlertDialog alertDialog;

    @Override
    public void showLoading() {
        alertDialog = LoadingDialogUtils.create(this, "");
        alertDialog.show();

    }

    @Override
    public void closeLoading() {
        if (alertDialog != null && alertDialog.isShowing())
            alertDialog.dismiss();
    }

    /**
     * 绑定presenter
     */
    @Override
    public void bindPresenter() {
        if (mPresenter == null) {
            mPresenter = new SearchPresenter();
        }
        mPresenter.bindView(this);
    }

    /**
     * 解除绑定presenter
     */
    @Override
    public void unbindPresenter() {
        mPresenter.unbindView();
    }


    @Override
    public void searchSuccessful(OrderData data) {
        LogUtils.e("data.list" + data.getData().size() + "page==" + page);
        if (page.equals("1")) {
            LogUtils.i("page==1");
            orderAdapter.clearInfoList();
            orderAdapter.addInfoList(data.getData());
        } else {
            orderAdapter.addInfoList(data.getData());
        }
        orderAdapter.notifyDataSetChanged();
    }

    @Override
    public void searchnomore(String msg) {
    ToastUtils.showShortToast(mActivity,msg);
    }

    @Override
    public void searchFailer(String msg) {
        ToastUtils.showShortToast(mActivity,msg);
    }

    public class OrderAdapter extends BaseRecyclerAdapter<OrderData.DataBean, OrderAdapter.ViewHolder> {
        @Override
        protected void onBindViewHolder(int position, ViewHolder holder) {
            OrderData.DataBean dataBean = getItem(position);
            holder.setvauels(dataBean);
        }

        @Override
        protected ViewHolder getViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(inflate(R.layout.item_orders, parent));

        }

        @Override
        protected void onBindItemClickListener(View v, int position) {
            super.onBindItemClickListener(v, position);

          Intent intent = new Intent(mActivity, OrderInfoActivity.class);
                intent.putExtra("data",getItem(position));
                startActivity(intent);

        }

        class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.company)
            TextView company;
            @BindView(R.id.driver_bottom)
            TextView driverBottom;
            @BindView(R.id.ordernum)
            TextView ordernum;
            @BindView(R.id.startaddress)
            TextView startaddress;
            @BindView(R.id.endaddress)
            TextView endaddress;
            @BindView(R.id.goodstime)
            TextView goodstime;
            @BindView(R.id.goods)
            TextView goods;
            @BindView(R.id.requiretime)
            TextView requiretime;
            @BindView(R.id.jiehuotime)
            TextView jhtime ;
            @BindView(R.id.ordertime)
            TextView orderTime ;
            @BindView(R.id.ordertimelin)
            LinearLayout orderLin ;
            @BindView(R.id.jiehuolin)
            LinearLayout jiehuolin ;
            @BindView(R.id.order_status)
            TextView orderstatus ;
            @BindView(R.id.disorder)
            TextView disorderbuttom ;
            ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            void setvauels(OrderData.DataBean dataBean) {
                if (TextUtils.equals(dataBean.getZT(),"4"))
                    disorderbuttom.setVisibility(View.GONE);
                else
                    disorderbuttom.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(dataBean.getQYMC()))
                    company.setText(dataBean.getQYMC());
                if (!TextUtils.isEmpty(dataBean.getFJRDZ()))
                    startaddress.setText(dataBean.getFJRDZ());
                if (!TextUtils.isEmpty(dataBean.getSJRDZ()))
                    endaddress.setText(dataBean.getSJRDZ());
                if (!TextUtils.isEmpty(dataBean.getYJSJ()))
                    requiretime.setText(dataBean.getYJSJ());
                else
                    requiretime.setText("未要求");
                if (!TextUtils.isEmpty(dataBean.getDH()))
                    ordernum.setText(dataBean.getDH());
                driverBottom.setText("");
                if (!TextUtils.isEmpty(dataBean.getCJSJ()))
                    orderTime.setText(dataBean.getCJSJ());
                if (!TextUtils.isEmpty(dataBean.getFHSJ()))
                    jhtime.setText(dataBean.getFHSJ());
                if (!dataBean.getGOODSLIST().isEmpty()) {
                    StringBuilder goodsName = new StringBuilder();
                    for (OrderData.DataBean.GOODSLISTBean goodslistBean : dataBean.getGOODSLIST()) {
                        goodsName = goodsName.append(goodslistBean.getMC()).append("|").append(goodslistBean.getSL()+goodslistBean.getDW()).append("  ");
                    }
                    goods.setText(goodsName);

                }
                if (!TextUtils.isEmpty(dataBean.getZT())){
                    orderstatus.setVisibility(View.VISIBLE);
                    orderstatus.setTextColor(getResources().getColor(R.color.white));
                    orderstatus.setBackgroundColor(getResources().getColor(R.color.theme_color));
                    if(TextUtils.equals(dataBean.getZT(),"0"))
                        orderstatus.setText("已发单");
                    if(TextUtils.equals(dataBean.getZT(),"1"))
                        orderstatus.setText("已分配");
                    if(TextUtils.equals(dataBean.getZT(),"2"))
                        orderstatus.setText("未接货");
                    if(TextUtils.equals(dataBean.getZT(),"3"))
                        orderstatus.setText("运输中");
                    if(TextUtils.equals(dataBean.getZT(),"4"))
                        orderstatus.setText("已完成");

                }
                disorderbuttom.setVisibility(View.GONE);
                jiehuolin.setVisibility(View.VISIBLE);
                orderLin.setVisibility(View.VISIBLE);
                driverBottom.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(dataBean.getGLXH())){
                    driverBottom.setText(dataBean.getGLXH());
                    driverBottom.setText("组合订单");
                    driverBottom.setTextColor(getResources().getColor(R.color.white));
                    driverBottom.setBackgroundColor(getResources().getColor(R.color.theme_color));
                    driverBottom.setEnabled(false);
                }else {
                    driverBottom.setVisibility(View.GONE);
                    driverBottom.setText("选择司机");
                    driverBottom.setEnabled(true);
                }



            }

        }
    }

}
